package com.sn.springboot_netty.filter;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Author fyy
 * @Description CrosXss拦截过滤
 * @Date 2020/5/20 9:33
 */
@WebFilter("/*")
@Component
public class CrosXssFilter implements Filter {

    private static Logger logger = LoggerFactory.getLogger(CrosXssFilter.class);

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        //跨域设置
        if(response instanceof HttpServletResponse){
            HttpServletResponse httpResponse = (HttpServletResponse) response;
            //通过在响应header中设置‘*’来允许来自所有域的跨域请求
            httpResponse.setHeader("Access-Control-Allow-Origin","*");
            //设置请求方式
            httpResponse.setHeader("Access-Control-Allow-Methods","*");
            httpResponse.setHeader("Access-Control-Max-Age", "86400");
            httpResponse.setHeader("Access-Control-Allow-Headers", "*");
        }
        //sql、xss过滤
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        logger.info("CrosXssFilter:url:{}",httpRequest.getRequestURI());
        XssHttpServletRequestWrapper xssHttpServletRequestWrapper = new XssHttpServletRequestWrapper(httpRequest);
        String param = getBodyString(xssHttpServletRequestWrapper.getReader());
        if(xssHttpServletRequestWrapper.checkSqlKeyWords(param)){
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json;charset=UTF-8");
            PrintWriter out = response.getWriter();
            out.write("参数中不允许存在sql关键字");
            return;
        }
        chain.doFilter(xssHttpServletRequestWrapper,response);
    }

    @Override
    public void init(FilterConfig config) throws ServletException {

    }

    @Override
    public void destroy() {

    }

    public static String getBodyString(BufferedReader br) {
        String inputLine;
        String str = "";
        try {
            while ((inputLine = br.readLine()) != null) {
                str += inputLine;
            }
            br.close();
        } catch (IOException e) {
            logger.error("过滤参数异常：{}",e.getMessage());
        }
        return str;
    }


}
